package log

import (
	"fmt"
	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
	"github.com/sirupsen/logrus"
	"io"
	"net/http"
	"os"
	"strings"
	"time"

	//"path"
	"runtime"
)

var Log = logrus.New()

const (
	green   = "\033[97;42m"
	white   = "\033[90;47;1m"
	yellow  = "\033[90;43m"
	red     = "\033[97;41m"
	blue    = "\033[97;44m"
	magenta = "\033[97;45m"
	cyan    = "\033[97;46m"
	reset   = "\033[0m"
)

func init() {

	Log.Level = logrus.DebugLevel
	Log.SetReportCaller(true)
	formatter := &logrus.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "2006-01-02 - Mon - 15:04:05",
		ForceColors:     true,
		CallerPrettyfier: func(frame *runtime.Frame) (function string, file string) {
			pwd, _ := os.Getwd()
			filename := strings.Replace(frame.File, pwd, "", -1)
			array := strings.Split(frame.Function, ".")
			return fmt.Sprintf("%20s()%s", array[len(array)-1], "|"),
				fmt.Sprintf("%-25s |%s %4d %s|", filename,
					white, frame.Line, reset)
		},
	}
	Log.SetFormatter(formatter)
	baseLogPath := "./logs/"
	_, err := os.Stat(baseLogPath)
	var mw io.Writer
	if err != nil {
		mw = os.Stdout
	} else {
		writer, _ := rotatelogs.New(
			baseLogPath+"%Y%m%d%H%M.log",
			rotatelogs.WithMaxAge(7*24*time.Hour),     // 文件最大保存时间
			rotatelogs.WithRotationTime(24*time.Hour), // 日志切割时间间隔
		)
		_, err = os.Stat(baseLogPath)
		if err != nil {
			fmt.Println(err)
		}
		mw = io.MultiWriter(os.Stdout, writer)
	}

	// 设置将日志输出到标准输出（默认的输出为stderr，标准错误）
	// 日志消息输出可以是任意的io.writer类型

	Log.SetOutput(mw)

}

func StatusCodeColor(code int) string {
	switch {
	case code >= http.StatusOK && code < http.StatusMultipleChoices:
		return green
	case code >= http.StatusMultipleChoices && code < http.StatusBadRequest:
		return white
	case code >= http.StatusBadRequest && code < http.StatusInternalServerError:
		return yellow
	default:
		return red
	}
}

func ResetColor() string {
	return reset
}

func MethodColor(method string) string {
	switch method {
	case "GET":
		return blue
	case "POST":
		return cyan
	case "PUT":
		return yellow
	case "DELETE":
		return red
	case "PATCH":
		return green
	case "HEAD":
		return magenta
	case "OPTIONS":
		return white
	default:
		return reset
	}
}
